import likeApi from "@/api/like.js";
import collectApi from "@/api/collect.js";
import commentApi from "@/api/comment.js";
import personalApi from "@/api/personal.js";

//地图相关
var map = null;
var mapDocLayer = null; //全国景区点要素图层.mapx 点要素聚合图
var TiandiMap_vec = null;
var TiandiMap_vectcia = null;
var TiandiMap_img = null;
var TiandiMap_imgcia = null;
var TiandiMap_ter = null;
var TiandiMap_tercia = null;
var beginExtent = null; //存放初始化时地图窗口的范围，用于复位
//空间查询相关
var interActionSource = null;
var interActionLayer = null; //交互绘制图层
var drawTool = null; //交互绘制类对象
var geomObj = null;
//查询结果-地图显示相关
var resultSource = null;
var resultLayer = null; //高亮显示查询结果的图层
var clickEvent = null; //地图点击事件
var popup = null;

export default {
  props: {
    queryType: {
      type: String,
      default: " ",
    },
  },
  directives: {
    drag(el, bindings) {
      el.onmousedown = function (e) {
        var disx = e.pageX - el.offsetLeft;
        var disy = e.pageY - el.offsetTop;
        document.onmousemove = function (e) {
          el.style.left = e.pageX - disx + "px";
          el.style.top = e.pageY - disy + "px";
        };
        document.onmouseup = function () {
          document.onmousemove = document.onmouseup = null;
        };
      };
    },
  },
  data() {
    return {
      tk: "fb3eec44ed909be3536962ff90220975", // 天地图密钥 fb3eec44ed909be3536962ff90220975 2329c6061242b26cba5d2d9b4da9a776
      layer_radio: 1,
      checkLayerShow: true,
      //条件查询相关
      conditionForm: {
        //条件
        name: "",
        province: "",
        leval: "",
      },
      conditionSQL: "1=1", //条件(属性)查询SQL语句
      provinceOptions: [
        {
          label: "北京市",
          value: "北京",
        },
        {
          label: "天津市",
          value: "天津",
        },
        {
          label: "河北省",
          value: "河北",
        },
        {
          label: "山西省",
          value: "山西",
        },
        {
          label: "内蒙古自治区",
          value: "内蒙古",
        },
        {
          label: "辽宁省",
          value: "辽宁",
        },
        {
          label: "吉林省",
          value: "吉林",
        },
        {
          label: "黑龙江省",
          value: "黑龙江",
        },
        {
          label: "上海市",
          value: "上海",
        },
        {
          label: "江苏省",
          value: "江苏",
        },
        {
          label: "浙江省",
          value: "浙江",
        },
        {
          label: "安徽省",
          value: "安徽",
        },
        {
          label: "福建省",
          value: "福建",
        },
        {
          label: "江西省",
          value: "江西",
        },
        {
          label: "山东省",
          value: "山东",
        },
        {
          label: "河南省",
          value: "河南",
        },
        {
          label: "湖北省",
          value: "湖北",
        },
        {
          label: "湖南省",
          value: "湖南",
        },
        {
          label: "广东省",
          value: "广东",
        },
        {
          label: "广西壮族自治区",
          value: "广西",
        },
        {
          label: "海南省",
          value: "海南",
        },
        {
          label: "重庆市",
          value: "重庆",
        },
        {
          label: "四川省",
          value: "四川",
        },
        {
          label: "贵州省",
          value: "贵州",
        },
        {
          label: "云南省",
          value: "云南",
        },
        {
          label: "西藏自治区",
          value: "西藏",
        },
        {
          label: "陕西省",
          value: "陕西",
        },
        {
          label: "甘肃省",
          value: "甘肃",
        },
        {
          label: "青海省",
          value: "青海",
        },
        {
          label: "宁夏回族自治区",
          value: "宁夏",
        },
        {
          label: "新疆维吾尔自治区",
          value: "新疆",
        },
        {
          label: "香港特别行政区",
          value: "香港",
        },
        {
          label: "澳门特别行政区",
          value: "澳门",
        },
        {
          label: "台湾省",
          value: "台湾",
        },
      ],
      levalOptions: [
        {
          label: "5A景区",
          value: "5A景区",
        },
        {
          label: "4A景区",
          value: "4A景区",
        },
        {
          label: "3A景区",
          value: "3A景区",
        },
      ],
      //空间查询相关
      drawType: null, //绘制类型
      spatialResultTitle: "",
      popupData: {
        id: "",
        name: "",
        img: "",
        leval: "",
        province: "",
        city: "",
        region: "",
        address: "",
        intro: "",
        like_num: 0,
        collect_num: 0,
        comment_num: 0,
      },
      isLike: false,
      isCollect: false,
      drawerShow: false,
      first_comment_content: "",
      second_comment_content: "",
      comment_list: [],
      // 查询结果-表格显示相关
      dvKey: 0, // dv自适应
      resultBoxShow: false, //查询结果盒子是否显示
      resultTableShow: false, //条件查询结果表格是否显示
      resultData: [], //条件查询结果数据
      tableTotal: 0, //结果总数
      tableCurrentPage: 1, //条件查询表格当前页
      tablePageSize: 20, //每页展示条数
      tableEmptyText: "", //没有数据时显示
      //登录用户的信息
      login_avatar: null,
      login_name: null,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    /*
     * 初始化
     */
    init() {
      this.initMapCon();
      this.initTDBaseMap();
      this.initControl();
      this.initSceneryMap();
      this.initInterAction();
      this.initResultLayer();
      this.initPopup();
      this.getLoginUserAvatar();
    },
    //初始化 地图容器
    initMapCon() {
      map = new ol.Map({
        target: "mapCon",
        view: new ol.View({
          projection: ol.proj.get("EPSG:3857"), //默认为 3857
          center: ol.proj.fromLonLat([104.912777, 34.730746]),
          minZoom: 1,
          zoom: 5,
        }),
      });
      // 地图窗口的初始范围
      beginExtent = map.getView().calculateExtent(map.getSize());
    },
    //初始化 天地图底图
    initTDBaseMap() {
      let layerOrigin_vec = new ol.layer.Tile({
        name: "天地图矢量图层",
        visible: true, //图层可见
        source: new ol.source.XYZ({
          url: "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=" + this.tk,
          crossOrigin: "Anonymous",
          wrapX: false,
        }),
      });
      let layerOrigin_vectcia = new ol.layer.Tile({
        name: "天地图矢量注记图层",
        visible: true, //图层可见
        source: new ol.source.XYZ({
          url: "http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=" + this.tk,
          crossOrigin: "Anonymous",
          wrapX: false,
        }),
      });
      TiandiMap_img = new ol.layer.Tile({
        name: "天地图影像图层",
        visible: false, //图层不可见
        source: new ol.source.XYZ({
          url: "http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + this.tk,
          wrapX: false,
        }),
      });
      TiandiMap_imgcia = new ol.layer.Tile({
        name: "天地图影像注记图层",
        visible: false, //图层不可见
        source: new ol.source.XYZ({
          url: "http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=" + this.tk,
          wrapX: false,
        }),
      });
      TiandiMap_ter = new ol.layer.Tile({
        name: "天地图地形晕染图层",
        visible: false, //图层不可见
        source: new ol.source.XYZ({
          url: "http://t0.tianditu.com/DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=" + this.tk,
          wrapX: false,
        }),
      });
      TiandiMap_tercia = new ol.layer.Tile({
        name: "天地图地形注记图层",
        visible: false, //图层不可见
        source: new ol.source.XYZ({
          url: "http://t0.tianditu.com/DataServer?T=cta_w&x={x}&y={y}&l={z}&tk=" + this.tk,
          wrapX: false,
        }),
      });
      //定义颜色转换方法
      let reverseFunc = function (pixelsTemp) {
        //蓝色
        for (var i = 0; i < pixelsTemp.length; i += 4) {
          var r = pixelsTemp[i];
          var g = pixelsTemp[i + 1];
          var b = pixelsTemp[i + 2];
          //运用图像学公式，设置灰度值
          var grey = parseInt((r + g + b) / 3);
          //将rgb的值替换为灰度值
          pixelsTemp[i] = grey;
          pixelsTemp[i + 1] = grey;
          pixelsTemp[i + 2] = grey;

          //基于灰色，设置为任意颜色 34, 52, 88
          var targetR = 34;
          var targetG = 52;
          var targetB = 88;
          var baseGrey = 242; //202
          pixelsTemp[i] = targetR + baseGrey - pixelsTemp[i];
          pixelsTemp[i + 1] = targetG + baseGrey - pixelsTemp[i + 1];
          pixelsTemp[i + 2] = targetB + baseGrey - pixelsTemp[i + 2];
        }
      };
      //openlayer 像素转换类，可以直接当做source使用
      const raster_vec = new ol.source.Raster({
        sources: [
          //传入图层，这里是天地图矢量图或者天地图矢量注记
          layerOrigin_vec,
        ],
        //这里设置为image类型，与官方示例不同，优化速度
        operationType: "image",
        operation: function (pixels, data) {
          //执行颜色转换方法，注意，这里的方法需要使用lib引入进来才可以使用
          reverseFunc(pixels[0].data);
          return pixels[0];
        },
        //线程数量
        threads: 20,
        //允许operation使用外部方法
        lib: {
          reverseFunc: reverseFunc,
        },
      });
      const raster_vectcia = new ol.source.Raster({
        sources: [
          //传入图层，这里是天地图矢量图或者天地图矢量注记
          layerOrigin_vectcia,
        ],
        //这里设置为image类型，与官方示例不同，优化速度
        operationType: "image",
        operation: function (pixels, data) {
          //执行颜色转换方法，注意，这里的方法需要使用lib引入进来才可以使用
          reverseFunc(pixels[0].data);
          return pixels[0];
        },
        //线程数量
        threads: 20,
        //允许operation使用外部方法
        lib: {
          reverseFunc: reverseFunc,
        },
      });
      //创建新图层，注意，必须使用 ImageLayer
      TiandiMap_vec = new ol.layer.Image({
        name: "天地图矢量图层",
        source: raster_vec,
      });
      TiandiMap_vectcia = new ol.layer.Image({
        name: "天地图矢量注记图层",
        source: raster_vectcia,
      });
      // 设置图层透明度
      TiandiMap_vec.setOpacity(0.8);
      TiandiMap_img.setOpacity(0.8);
      TiandiMap_vectcia.setOpacity(0.8)
      //添加图层
      map.addLayer(TiandiMap_ter);
      map.addLayer(TiandiMap_tercia);
      map.addLayer(TiandiMap_img);
      map.addLayer(TiandiMap_imgcia);
      map.addLayer(TiandiMap_vec);
      map.addLayer(TiandiMap_vectcia);
    },
    //天地图图层控制
    tdLayerChange(layerList) {
      TiandiMap_vec.setVisible(this.layer_radio==1);
      TiandiMap_vectcia.setVisible(this.layer_radio==1);
      TiandiMap_img.setVisible(this.layer_radio==2);
      TiandiMap_imgcia.setVisible(this.layer_radio==2);
      TiandiMap_ter.setVisible(this.layer_radio==3);
      TiandiMap_tercia.setVisible(this.layer_radio==3);
    },
    //初始化 地图控件
    initControl() {
      // 鼠标位置
      let mousePositionControl = new ol.control.MousePosition({
        //坐标格式
        coordinateFormat: ol.coordinate.createStringXY(4),
        //地图投影坐标系（若未设置则输出为默认投影坐标系下的坐标）
        projection: "EPSG:4326",
        //坐标信息显示样式类名，默认是'ol-mouse-position'
        className: "custom-mouse-position",
        //显示鼠标位置信息的目标容器
        target: document.getElementById("mouse-position"),
        //未定义坐标的标记
        undefinedHTML: "&nbsp;",
      });
      map.addControl(mousePositionControl);
      //实例化ZoomSlider控件并加载到地图容器中
      let zoomslider = new ol.control.ZoomSlider();
      map.addControl(zoomslider);
      //缩放至范围,复位
      let zoomToExtent = new ol.control.ZoomToExtent({
        extent: beginExtent,
      });
      map.addControl(zoomToExtent);
    },
    //初始化 全国景区图层
    initSceneryMap() {
      //初始化地图文档图层对象
      mapDocLayer = new Zondy.Map.Doc("全国景区点要素图层", "全国景区点要素图层", {
        ip: window.server.GIS_IP,
        port: window.server.GIS_PORT,
      });
      //将地图文档图层加载到地图中
      map.addLayer(mapDocLayer);
    },
    //初始化 交互绘制矢量图层 - 空间查询
    initInterAction() {
      if (this.queryType != "spatial") return;
      //实例化一个矢量图层作为交互绘制层
      interActionSource = new ol.source.Vector({ wrapX: false });
      interActionLayer = new ol.layer.Vector({
        name: "交互绘制图层",
        source: interActionSource,
        style: new ol.style.Style({
          //填充色
          fill: new ol.style.Fill({
            color: "rgba(255, 255, 255, 0.2)",
          }),
          //边线样式
          stroke: new ol.style.Stroke({
            color: "#ffcc33",
            width: 2,
          }),
        }),
      });
      //将交互绘制层添加到地图容器中
      map.addLayer(interActionLayer);
    },
    //初始化 查询结果高亮显示图层
    initResultLayer() {
      resultSource = new ol.source.Vector({ wrapX: false });
      resultLayer = new ol.layer.Vector({
        name: "查询结果显示图层",
        source: resultSource,
        style: new ol.style.Style({
          image: new ol.style.Icon({
            src: require("@/assets/spot.png"),
            scale: 0.3,
          }),
        }),
      });
      map.addLayer(resultLayer);
    },
    //初始化 popup
    initPopup() {
      popup = new ol.Overlay({
        //要转换成overlay的HTML元素
        element: document.getElementById("popup"),
        //当前窗口可见
        autoPan: true,
        //Popup放置的位置
        positioning: "bottom-center",
        //是否应该停止事件传播到地图窗口
        stopEvent: false,
        autoPanAnimation: {
          duration: 300,
        },
      });
      map.addOverlay(popup);
      popup.setPosition(undefined);
    },
    //获取登录用户的头像
    async getLoginUserAvatar() {
      const login_user = await personalApi.getInfo();
      this.login_avatar = login_user.data.avatar;
      this.login_name = login_user.data.user_name;
    },

    /*
     * 地图文档查询方法
     */
    docFeatureQuery() {
      //初始化查询结构对象，设置查询结构包含几何信息
      const queryStruct = new Zondy.Service.QueryFeatureStruct();
      //是否包含几何图形信息
      queryStruct.IncludeGeometry = true;
      //是否包含属性信息
      queryStruct.IncludeAttribute = true;
      //是否包含图形显示参数
      queryStruct.IncludeWebGraphic = false;
      //实例化查询参数对象
      const queryParam = new Zondy.Service.QueryParameter({
        resultFormat: "json",
        struct: queryStruct,
      });
      if (this.queryType == "condition") {
        //条件查询-设置条件
        if (this.conditionSQL != null && this.conditionSQL != "1=1") queryParam.where = this.conditionSQL;
      } else if (this.queryType == "spatial") {
        //指定查询规则
        const rule = new Zondy.Service.QueryFeatureRule({
          //是否将要素的可见性计算在内
          EnableDisplayCondition: false,
          //是否完全包含
          MustInside: false,
          //是否仅比较要素的外包矩形
          CompareRectOnly: false,
          //是否相交
          Intersect: true,
        });
        queryParam.rule = rule;
        queryParam.geometry = geomObj;
      }
      //设置查询分页号
      queryParam.pageIndex = this.tableCurrentPage - 1;
      //设置每页记录数
      queryParam.recordNumber = this.tablePageSize;
      //实例化地图文档查询服务对象
      const queryService = new Zondy.Service.QueryDocFeature(queryParam, "全国景区点要素图层", 0, {
        ip: window.server.GIS_IP,
        port: window.server.GIS_PORT,
      });
      queryService.query(this.docQuerySuccess, this.docQueryError);
    },
    //地图文档查询 - 成功回调
    docQuerySuccess(result) {
      if (result.TotalCount == 0) {
        this.tableEmptyText = "暂无数据";
        return;
      }
      //初始化Zondy.Format.PolygonJSON类
      let format = new Zondy.Format.PolygonJSON();
      //将MapGIS要素JSON反序列化为ol.Feature类型数组
      let features = format.read(result);
      this.afterQuery(result, features);
    },
    //地图文档查询 - 失败回调
    docQueryError(e) {
      this.tableEmptyText = "暂无数据";
    },
    //查询前重置数据
    beforeQuery() {
      this.tableEmptyText = "正在查询中...";
      //显示查询结果盒子
      this.resultBoxShow = true;
      this.resultTableShow = true;
      this.$nextTick(() => {
        this.dvKey++;
      });
      //重置数据
      this.resultData = [];
      this.tableTotal = 0;
      this.tableCurrentPage = 1;
      this.tablePageSize = this.queryType == "condition" ? 20 : 5;
      popup.setPosition(undefined);
    },
    //查询后处理数据
    afterQuery(result, features) {
      //表格显示结果
      this.refreshTableResult(result, features);
      //地图显示结果
      this.refreshMapResult(features);
    },

    /*
     * 查询结果-表格显示
     */
    //表格显示查询结果
    refreshTableResult(result, features) {
      //数据
      this.resultData = [];
      for (let i = 0; i < features.length; i++) {
        this.resultData.push(features[i].getProperties().values_);
      }
      //总数
      this.tableTotal == 0 ? (this.tableTotal = result.TotalCount) : null;
    },
    //清空表格查询结果
    removeTableResult() {
      //关闭结果表格盒子
      this.resultBoxShow = false;
      this.resultTableShow = false;
      this.resultData = [];
      this.tableTotal == 0;
      if (this.queryType == "condition") {
        //重置查询条件
        this.conditionForm.name = "";
        this.conditionForm.province = "";
        this.conditionForm.leval = "";
      }
    },
    //拼接结果表格中的'所在地'字段
    getPlaceName(item) {
      let res = item.province;
      if (item.province != "北京" && item.province != "天津" && item.province != "上海" && item.province != "重庆") {
        if (item.city != null && item.city != "") res = res + "·" + item.city;
      }
      if (item.region != null && item.region != "") res = res + "·" + item.region;
      return res;
    },
    //结果表格 - 每页展示条数改变，重新获取第0页数据
    tableSizeChange() {
      this.tableCurrentPage = 1;
      this.docFeatureQuery();
    },
    //结果表格 - 当前页改变，获取新当前页数据
    tableCurrentChange() {
      this.docFeatureQuery();
      popup.setPosition(undefined);
    },
    //收起、展开结果表格按钮，dv边框自适应
    resultTableChange() {
      this.resultTableShow = !this.resultTableShow;
      this.$nextTick(() => {
        this.dvKey++;
      });
    },
    //关闭查询结果盒子按钮
    resultBoxClose() {
      //关闭查询结果盒子
      this.resultBoxShow = false;
      this.resultTableShow = false;
    },

    /*
     *  查询结果-地图显示
     */
    //更新地图显示的查询结果
    refreshMapResult(features) {
      //隐藏景区点要素图层
      if (this.drawType != "Point") mapDocLayer && mapDocLayer.getVisible() ? mapDocLayer.setVisible(false) : null;
      //空间查询 - 清空绘制内容
      if (this.queryType == "spatial") this.clearDraw();
      //添加查询结果要素
      resultSource.clear();
      resultSource.addFeatures(features);
      //自适应视图
      if (this.drawType != "Point") {
        const extent = resultSource.getExtent();
        map.getView().fit(extent);
        map.getView().setZoom(map.getView().getZoom() - 1);
      }
      //添加要素点击事件 - 弹出popup
      this.addClickEvent();
    },
    //清空地图显示的查询结果
    removeMapResult() {
      //清空显示内容
      resultSource.clear();
      //移除要素点击事件 - 弹出popup
      this.removeClickEvent();
    },
    //显示全国景区点要素图层
    showSceneryLayer() {
      //显示
      mapDocLayer && mapDocLayer.getVisible() ? null : mapDocLayer.setVisible(true);
    },
    //复位全国景区点要素图层
    refreshSceneryLayer() {
      //复位
      let r = map.getView().getResolutionForExtent(beginExtent, map.getSize());
      map.getView().setResolution(r);
      map.getView().setCenter(ol.extent.getCenter(beginExtent));
    },

    /*
     *条件查询相关
     */
    //条件查询 - 查询按钮被点击
    conditionQueryBtn() {
      //查询条件
      this.conditionSQL = "1=1";
      if (this.conditionForm.name != null && this.conditionForm.name != "") {
        this.conditionSQL += " AND name like '%" + this.conditionForm.name + "%'";
      }
      if (this.conditionForm.province != null && this.conditionForm.province != "") {
        this.conditionSQL += " AND province = '" + this.conditionForm.province + "'";
      }
      if (this.conditionForm.leval != null && this.conditionForm.leval != "") {
        this.conditionSQL += " AND leval = '" + this.conditionForm.leval + "'";
      }
      this.beforeQuery();
      this.docFeatureQuery();
    },
    //条件查询 - 重置按钮被点击

    conditionResetBtn() {
      //清空表格显示结果
      this.removeTableResult();
      //移除地图显示结果
      this.removeMapResult();
      this.showSceneryLayer();
      this.refreshSceneryLayer();
    },

    /*
     * 空间查询相关
     */
    //空间查询 - 交互绘制按钮被点击
    spatialQueryBtn(type) {
      this.clearDraw();
      this.removeMapResult();
      this.removeTableResult();
      this.showSceneryLayer();
      this.drawType = type;
      let geometryFunction = null;
      if (type == "Square") {
        type = "Circle";
        //设置几何信息变更函数，即设置长方形的坐标点
        geometryFunction = ol.interaction.Draw.createBox();
      }
      //实例化交互绘制类对象并添加到地图容器中
      drawTool = new ol.interaction.Draw({
        type: type,
        //绘制层数据源
        source: interActionSource,
        geometryFunction: geometryFunction,
      });
      map.addInteraction(drawTool);
      //绘制结束触发函数
      drawTool.on("drawend", this.drawToolCallback);
    },
    //绘制结束的回调函数
    drawToolCallback(feature) {
      if (this.drawType == "Point") {
        //点查询：创建一个用于查询的点
        this.spatialResultTitle = "点查询结果";
        geomObj = new Zondy.Object.Point2D();
        geomObj.setByOL(feature.feature.values_.geometry);
        //设置点的查询半径
        const zoom = map.getView().getZoom();
        if (zoom <= 5) geomObj.nearDis = 30000;
        else if (zoom <= 7) geomObj.nearDis = 25000;
        else if (zoom <= 10) geomObj.nearDis = 10000;
        else geomObj.nearDis = 100;
      } else if (this.drawType == "Circle") {
        //圆查询：创建一个用于查询的圆
        this.spatialResultTitle = "圆查询结果";
        geomObj = new Zondy.Object.Circle();
        geomObj.setByOL(feature.feature.values_.geometry);
      } else if (this.drawType == "Square") {
        //拉框查询：创建一个用于查询的区
        this.spatialResultTitle = "拉框查询结果";
        geomObj = new Zondy.Object.Polygon();
        geomObj.setByOL(feature.feature.values_.geometry);
      } else {
        //多边形查询：创建一个用于查询的区
        this.spatialResultTitle = "多边形查询结果";
        geomObj = new Zondy.Object.Polygon();
        geomObj.setByOL(feature.feature.values_.geometry);
      }
      this.beforeQuery();
      this.docFeatureQuery();
    },
    //清除绘制对象、绘制内容
    clearDraw() {
      drawTool != null ? map.removeInteraction(drawTool) : null;
      interActionSource != null ? interActionSource.clear() : null;
    },
    //空间查询 - 清空按钮被点击
    spatialClearBtn() {
      this.removeTableResult();
      this.clearDraw();
      this.removeMapResult();
      this.showSceneryLayer();
      this.refreshSceneryLayer();
    },

    /*
     * popup 相关函数
     */
    //添加点击事件
    addClickEvent() {
      clickEvent = map.on("click", async (e) => {
        let feature = map.forEachFeatureAtPixel(
          e.pixel,
          (feature) => {
            return feature;
          },
          {
            hitTolerance: 20, //误差
            layerFilter: (layer) => {
              return layer.get("name") === "查询结果显示图层";
            },
          }
        );
        if (feature) {
          popup.setPosition(undefined);
          let values = feature.getProperties().values_;
          this.popupData = { ...values, like_num: 0, collect_num: 0, comment_num: 0 };
          let res = await this.getPopupData();
          let coordinate = feature.getGeometry().flatCoordinates;
          popup.setPosition(coordinate);
        }
      });
    },
    //获取点赞、收藏情况，获取点赞数、收藏数、评论数
    async getPopupData(feature) {
      const allPromise = [
        likeApi.queryLike(this.popupData.id, 0),
        collectApi.queryCollect(this.popupData.id, 0),
        likeApi.getNum(this.popupData.id, 0),
        collectApi.getNum(this.popupData.id, 0),
        commentApi.getNum(this.popupData.id, 0),
      ];
      const result = await Promise.all(allPromise);
      this.isLike = result[0].data;
      this.isCollect = result[1].data;
      this.popupData.like_num = result[2].data;
      this.popupData.collect_num = result[3].data;
      this.popupData.comment_num = result[4].data;
    },
    //popup点赞按钮
    async like_click() {
      const res = await likeApi.changeLike(this.popupData.id, 0);
      this.popupData.like_num = res.data;
      this.isLike = !this.isLike;
    },
    //popup收藏按钮
    async collect_click() {
      const res = await collectApi.changeCollect(this.popupData.id, 0);
      this.popupData.collect_num = res.data;
      this.isCollect = !this.isCollect;
    },
    //popup评论按钮
    async comment_click() {
      this.drawerShow = true;
      this.first_comment_content = "";
      this.second_comment_content = "";
      //获取评论列表
      const res = await this.getComment();
    },
    //移除点击事件
    removeClickEvent() {
      popup.setPosition(undefined);
      ol.Observable.unByKey(clickEvent);
    },
    //关闭popup
    closePopup() {
      popup.setPosition(undefined);
    },

    /*
     * drawer 相关函数
     */
    //获取评论列表、评论数
    async getComment() {
      this.comment_list = [];
      const res = await commentApi.getComment(this.popupData.id, 0);
      this.comment_list = res.data.list;
      this.popupData.comment_num = res.data.total;
    },
    //新增评论
    async addComment(item, item_second) {
      let params = {};
      params.topic_id = this.popupData.id;
      params.topic_type = 0;
      if (item == null) {
        // 一级评论
        params.type = 0;
        params.content = this.first_comment_content;
      } else {
        //二级评论
        params.type = 1;
        params.content = this.second_comment_content;
        if (item_second) {
          params.first_comment_id = item.comment_id;
          params.to_comment_id = item_second.comment_id;
          params.to_user_id = item_second.from_user_id;
          params.to_user_name = item_second.from_user_name;
        } else {
          params.first_comment_id = item.comment_id;
          params.to_comment_id = item.comment_id;
          params.to_user_id = item.from_user_id;
          params.to_user_name = item.from_user_name;
        }
      }
      //新增
      const res = await commentApi.addComment(params);
      this.first_comment_content = "";
      this.second_comment_content = "";
      if (item != null) item.reply_show = false;
      //获取评论列表、评论数
      this.getComment();
    },
    //删除评论
    async deleteComment(item) {
      //删除
      const res = await commentApi.deleteComment(item.comment_id);
      //获取评论列表、评论数
      this.getComment();
    },
    //删除按钮是否显示
    isDeleteShow(item) {
      return this.login_name == item.from_user_name;
    },
    //回复、收起按钮被点击
    showReply(item) {
      item.reply_show = !item.reply_show;
      if (item.reply_show) {
        //回复按钮被点击
        //聚焦input
        this.$nextTick(() => {
          this.$refs[item.comment_id.toString()][0].focus();
        });
        //关闭其他回复input
        const length = this.comment_list.length;
        for (let i = 0; i < length; i++) {
          if (this.comment_list[i].reply_show && this.comment_list[i].comment_id != item.comment_id) {
            this.comment_list[i].reply_show = false;
            return;
          }
          if (this.comment_list[i].children != null) {
            const length_ = this.comment_list[i].children.length;
            for (let j = 0; j < length_; j++) {
              if (this.comment_list[i].children[j].reply_show && this.comment_list[i].children[j].comment_id != item.comment_id) {
                this.comment_list[i].children[j].reply_show = false;
                return;
              }
            }
          }
        }
      }
      this.second_comment_content = "";
    },
  },
};
